const express = require('express');
const router = express.Router();
const { ItemLabel, Category } = require('../models');
const { Op } = require('sequelize');

// 创建标签
router.post('/create', async (req, res) => {
    const { name, color, sort = 0, categoryId } = req.body;
    if (!name) {
        return res.status(400).json({ code: 400, message: '标签名称不能为空' });
    }

    try {
        const label = await ItemLabel.create({ name, color, sort, categoryId });
        res.json({ code: 200, message: '创建成功', data: label });
    } catch (error) {
        console.error('[label] 创建失败:', error);
        res.status(500).json({ code: 500, message: '创建标签失败', error: error.message });
    }
});

// 获取标签列表
router.post('/list', async (req, res) => {
    const { title, categoryId } = req.body;

    const whereClause = {};
    if (title) {
        whereClause.name = { [Op.like]: `%${title}%` };
    }
    if (categoryId) {
        whereClause.categoryId = categoryId;
    }

    try {
        const labels = await ItemLabel.findAll({
            where: whereClause,
            include: [{
                model: Category,
                as: 'category',
                attributes: ['id', 'name']  // 只取分类的 id 和 name
            }],
            order: [['sort', 'ASC'], ['id', 'ASC']],
        });

        res.json({ code: 200, message: '', data: labels });
    } catch (error) {
        console.error('[label] 获取失败:', error);
        res.status(500).json({ code: 500, message: '获取标签失败', error: error.message });
    }
});



// 更新标签
router.post('/update', async (req, res) => {
    const { id, name, color, sort, categoryId } = req.body;

    if (!id || !name || !categoryId) {
        return res.status(400).json({ code: 400, message: 'ID、标签名称和分类ID不能为空' });
    }

    try {
        const label = await ItemLabel.findByPk(id);
        if (!label) {
            return res.status(404).json({ code: 404, message: '标签不存在' });
        }

        label.name = name;
        label.color = color || null;
        label.sort = sort || 0;
        label.categoryId = categoryId;
        await label.save();

        res.json({ code: 200, message: '更新成功', data: label });
    } catch (error) {
        console.error('[label] 更新失败:', error);
        res.status(500).json({ code: 500, message: '更新标签失败', error: error.message });
    }
});


// 删除标签
router.post('/delete', async (req, res) => {
    const { id } = req.body;
    if (!id) {
        return res.status(400).json({ code: 400, message: 'ID 不能为空' });
    }

    try {
        const label = await ItemLabel.findByPk(id);
        if (!label) {
            return res.status(404).json({ code: 404, message: '标签不存在' });
        }

        await label.destroy();
        res.json({ code: 200, message: '删除成功' });
    } catch (error) {
        console.error('[label] 删除失败:', error);
        res.status(500).json({ code: 500, message: '删除标签失败', error: error.message });
    }
});

module.exports = router;
